package com.aitemv.base.impl;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;

import com.aitemv.base.BaseDao;
import com.aitemv.base.BaseEntity;
import com.aitemv.base.BaseService;
import com.aitemv.utils.PageBean;
import com.aitemv.utils.PropertiesUtil;

/**
 * @ClassName: BaseServiceImpl 
 * @Description: service基类
 * @author java_lyvee@126.com 
 * @date 2014-1-13 上午11:21:17 
 *
 */
public class BaseServiceImpl implements BaseService {
	@Autowired
	protected BaseDao baseDao;

	/**
	 * @param <T>
	 * @param flagPage 是否分页
	 * @param page	page对象
	 * @param sqlkey 获得sql的key
	 * @param mapper
	 * @param objs	查询参数
	 * @param where where条件
	 * @return
	 * @throws IOException
	 */
	public <T extends BaseEntity> List<T> findByPage(boolean flagPage,
			PageBean page, String sqlkey,@SuppressWarnings("rawtypes") ParameterizedBeanPropertyRowMapper mapper,
			List<Object> param, String where, Class<T> className)
			throws IOException {
		StringBuffer sql = new StringBuffer();//sql
		String pageSql = "";//mysql分页
		List<T> entityList = null;//查询出来的结果集
		if (flagPage) {
			pageSql = PropertiesUtil.load("mysql_page");
			param.add(page.getStartPage());//分页信息
			param.add(page.getPageSize());
		}
		Object[] objs = new Object[param.size()];//一个list长度的数组
		for(int i=0;i<param.size();i++){
			objs[i] = param.get(i);
		}
		sql.append(PropertiesUtil.load(sqlkey));//从配置文件取得sql语句
		sql.append(where);//where条件
		sql.append(pageSql);
		//sql.append(page.getStartPage()+","+page.getPageSize());
		if (mapper == null) {
			entityList = baseDao.getObjList(sql.toString(), className, objs);
		} else {
			entityList = baseDao.getObjList(sql.toString(), mapper, objs);
		}
		return entityList;
	}

	/***查询共有多少条记录****/
	public int findUserCount(String sqlKey) {
		String sql = "";
		try {
			sql = PropertiesUtil.load(sqlKey);
		} catch (IOException e) {
			e.printStackTrace();
		}
		Map<String, ?> map = baseDao.find(sql, null);
		long count = (Long) map.get("totalSize");
		return (int) count;
	}
	
}
